﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class ContractDetails : Form, IValidating
    {
        internal DataRow contract;        

        public ContractDetails()
        {
            InitializeComponent();
        }

        public ContractDetails(DataRow row, InputAction action)
            : this()
        {
            #region populating checkboxes
            var positions = new List<StaffRole>
                                {
                                    new StaffRole(Position.StoreManager),
                                    new StaffRole(Position.AssistantManager),
                                    new StaffRole(Position.StoreDeputy),
                                    new StaffRole(Position.StoreAssistant)
                                };
            cbPosition.DataSource = positions;
            cbPosition.DisplayMember = "PositionName";
            cbPosition.ValueMember = "position";
            #endregion

            if (action == InputAction.Update)
            {
                contract = row;
            }
            else
            {
                contract = SQLiteAccess.SpawnContractRow();
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    contract[i] = row[i];
                    }
            }
            AbsorbRowData(contract);            
             
           // _contract = SQLiteAccess.SpawnContractRow();            
        }

        public static KeyValuePair<FormValidationResult, string> DoesValidate(ComboBox position, NumericUpDown hours)
        {
            var validated = FormValidationResult.Fine;
            var message = String.Empty;

            if (position.SelectedValue == null)
            {
                message += "*\tSpecify the job position\n";
                validated = FormValidationResult.Error;
            }
            if (hours.Value < 1)
            {
                message += "*\tSpecify the number of hours on the contract\n";
                validated = FormValidationResult.Error;
            }
            
            return new KeyValuePair<FormValidationResult, string>(validated, message);
        }

        /// <param Name="last">the date of the last _contract - this one cannot be antedated</param>
        public ContractDetails(DateTime last) : this()
        {
            dtStartingDate.MinDate = last.Date.AddDays(1);
        }

        public static void FillRow(DataRow contract, DateTimePicker date, bool hired, ComboBox jobtitle, bool offprod, NumericUpDown hours, NumericUpDown holidays, TextBox comments)
        {
            contract[2] = date.Value.Date;
            contract[3] = hired ? 1 : 0;

            var p = (Position)jobtitle.SelectedValue;            
            // if off productivity - we light the last bit up
            p = offprod ? (p | Position.Trainee) : p;
            contract[4] = (int)p;

            contract[5] = hours.Value;
            contract[6] = holidays.Value;
            contract[7] = comments.Text;
        }

        private void FillRow()
        {            
            contract[2] = dtStartingDate.Value.Date;
            contract[3] = rbNewContract.Checked ? 1 : 0; // Hired? or fired

            var p = (Position)cbPosition.SelectedValue;
            p = cbOffProd.Checked ? (p | Position.Trainee) : p;            
            contract[4] = (int)p;
            
            contract[5] = nudContractHrs.Value;
            contract[6] = nudHolidays.Value;
            contract[7] = tbComments.Text.Trim();
        }

        private void AbsorbRowData(DataRow pContract)
        {
            // two separate try-catch blocks, because it'pShift two different parsings
            // if we can't get the first one done, I still want to try the other.
            try
            {
                dtStartingDate.Value = DateTime.Parse(pContract[2].ToString()).Date;                
            }
            catch { }
            try
            {                
                var i = (Int64)pContract[4];
                var p = i.To<Position>();
                cbOffProd.Checked = ((p & Position.Trainee) > 0);
                p = p.GetAsOnProd(); // we lit the "trainee" flag off (if it'pShift On)

                var toFind = new StaffRole(p);
                cbPosition.SelectedIndex = cbPosition.Items.Contains(toFind) ? cbPosition.Items.IndexOf(toFind) : 0;
            }
            catch { }
            rbNewContract.Checked = (bool)pContract[3];
            rbTermination.Checked = !(bool)pContract[3];

            nudContractHrs.Value = (Int64)pContract[5];
            nudHolidays.Value = (Int64)pContract[6];
            tbComments.Text = pContract[7].ToString();
        }

        private void rbTermination_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Control c in tblJobDetails.Controls)
                if(c.GetType() != typeof(DateTimePicker))
                    c.Enabled = rbNewContract.Checked;
            lbStartingDate.Text = rbNewContract.Checked ? "Starting date" : "Date of effect";
        }

        public KeyValuePair<FormValidationResult, string> DoesValidate()
        {
            if (!(rbNewContract.Checked || rbTermination.Checked))
            {
                var message = "*\tYou have to choose whether the employee is to be hired \n ('new contract') or laid off ('termination of employment').\n";
                return new KeyValuePair<FormValidationResult, string>
                    (FormValidationResult.Error,
                    message);
            }
            var result = DoesValidate(cbPosition, nudContractHrs);
            return result;
                        
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var validated = DoesValidate();
            if (validated.Key == FormValidationResult.Error)
            {
                var message = validated.Value;
                MessageBox.Show(
                    message,
                    Resources.MESSAGEBOX_ERROR_FormValidationResultERROR_CAPTION,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            if (validated.Key == FormValidationResult.Problem)
            {
                var message = validated.Value;
                var decision = MessageBox.Show(
                    message,
                    Resources.MESSAGEBOX_QUESTION_FormValidationResultPROBLEM_CAPTION,
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question);
                if (decision == DialogResult.Cancel)
                {
                    return;
                }
            }
            FillRow();

            DialogResult = DialogResult.OK;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            rbTermination.Checked = false;
            rbNewContract.Checked = false;
            tbComments.Text = String.Empty;
        }
    }
}
